# main.py
from flask import Flask, request, jsonify
import threading
import time
import logging
from config import load_config, config
from model_manager import ModelManager, auto_unload_models
from bot_factory import create_bot

app = Flask(__name__)
load_config()
model_manager = ModelManager()

# Start the auto-unload thread
unload_thread = threading.Thread(target=auto_unload_models, daemon=True)
unload_thread.start()

@app.route('/wechat', methods=['POST'])
def wechat():
    data = request.json
    user_id = data.get('user_id')
    message = data.get('message')

    if not user_id or not message:
        return jsonify({"error": "Missing user_id or message"}), 400

    if message.startswith("/switch"):
        model_name = message.split(" ")[1]
        success, msg = model_manager.load_model(model_name)
        return jsonify({"status": "success" if success else "error", "message": msg})

    current_model = config.get("default_model")
    model_config = model_manager.get_model(current_model)
    if not model_config:
        return jsonify({"error": "Model not loaded"}), 500

    bot = create_bot(model_config["bot_type"], model_config)
    response = bot.get_response(message)

    return jsonify({
        "user_id": user_id,
        "message": response
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=config.get("wechatmp_port", 8989))
